import { Request, catchAwait, MessageCenter } from "utils-lib-js";
import { config } from "../config.js";
export class NewBingServer extends MessageCenter {
    opts;
    _config;
    bingInfo;
    bingRequest;
    constructor(opts, _config = config) {
        super();
        this.opts = opts;
        this._config = _config;
        const { bingUrl } = this._config;
        this.bingRequest = new Request(bingUrl);
        this.initServer();
    }
    throwErr(err) {
        this.emit("new-bing:server:error", err);
    }
    async reset() {
        this.clearBing();
        const bingInfo = await this.createConversation();
        this.init(bingInfo);
    }
    clearBing() {
        this.bingInfo = null;
    }
    init(bingInfo) {
        this.bingInfo = bingInfo;
    }
    initServer() {
        this.bingRequest.use("error", console.error);
    }
    async createConversation() {
        const { _config, opts, bingInfo } = this;
        const { agent } = opts;
        if (bingInfo)
            return bingInfo;
        const { cookie } = _config;
        const [err, res] = await catchAwait(this.bingRequest.GET("/turing/conversation/create", {}, null, {
            headers: { cookie },
            agent
        }));
        if (err)
            return this.throwErr(err);
        return res;
    }
}
